﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using openlaunch;
using System.IO;
using ComponentOwl.BetterListView;
using System.Threading;
using System.Reflection;
using System.Net;
namespace OpenLauncher
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static PluginCollection plugins = new PluginCollection();
        void showform()
        {
            Application.Run(new SplashScreen()); // Show Splashscreen
        }
        void checkupdates()
        {
            //Make a web request
            //To check the latest version
            
            //TODO:
            //Add Update code here
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Thread ggg = new Thread(new ThreadStart(showform));
            Thread update = new Thread(new ThreadStart(checkupdates));
            update.Start(); //Start update thread to check for updates
            ggg.Start(); //Start the splash screen thread
            //Create directory
            Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"/Styko Company/OpenLaunch/");
            try
            {
                string path = Application.StartupPath + @"/plugins/";
                string[] f = Directory.GetFiles(path); //Grab files in plugins directory
                foreach (string g in f) //Loop through list of files.
                {
                    if (g.Substring(g.Length - 3, 3) == "olp")
                    {
                        byte[] gg = PluginProtector.DecryptData(File.ReadAllBytes(g)); //Decrypt the assembly
                        var assm = Assembly.Load(gg); //Load decrypted assembly into memory
                        foreach (Type tsype in assm.GetTypes())
                        {
                            foreach (var tys in tsype.GetInterfaces()) //Loop through interfaces
                            {
                                if (tys.Name == "OpenPlugin") //Check to see if interface matches ours.
                                {
                                    try
                                    {
                                        OpenPlugin oplugin = (OpenPlugin)Activator.CreateInstance(tsype); //Create instance of plugin
                                        oplugin.OnStart(); //Run plugin startup task
                                        FillPluginList(oplugin); //Add to interface
                                        plugins.Add(oplugin); //Add plugin to plugin list
                                        break;
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                Thread.Sleep(2000); //Finish the splash screen thread
                ggg.Abort(); //Abort the splash screen page
            }
            catch
            {
            }
        }
        public void FillPluginList(OpenPlugin mgm)
        {
                BetterListViewItem gg = new BetterListViewItem(); //Create a new list item
                gg.Text = mgm.Name; //Extract the name of the plugin
                gg.Image = AutoSizeImage(mgm.ProgramImage, pictureBox1, PictureBoxSizeMode.CenterImage); //Resize the image
                betterListView1.Items.Add(gg); //Add to the list
        }
        private void OnPluginClick(object sender, System.EventArgs e)
        {
            ToolStripItem item = (ToolStripItem)sender; //Create a new toolstrip item based off of the text of the plugin
            string plugName = item.Text.Replace("&", ""); //Replace ampersand
            ExecutePlugin(plugName); //Execute the plugin
        }
        private void ExecutePlugin(string PlugName)
        {
            foreach (OpenPlugin plugin in plugins)
            {
                if (plugin.Name == PlugName)
                {
                    plugin.Run();
                }
            }
        }
        void betterListView1_DoubleClick(object sender, System.EventArgs e)
        {
            //Make sure selected items are not low.
            if (betterListView1.SelectedItems.Count != 0 && betterListView1.SelectedItems.Count > 0)
            {
                //Execute teh plugin
                ExecutePlugin(betterListView1.SelectedItems[0].Text);
            }
        }
        public static Image AutoSizeImage(Image Imagef, PictureBox picbox, PictureBoxSizeMode pSizeMode)
        {
            picbox.Image = null;
            picbox.SizeMode = pSizeMode;
                Bitmap imgOrg;
                Bitmap imgShow;
                Graphics g;
                double divideBy, dividebyH, dividebyW;
                divideBy = 0;
                imgOrg = (Bitmap)Imagef;
                dividebyW = imgOrg.Width / picbox.Width;
                dividebyH = imgOrg.Height /picbox.Height;
                if(dividebyW > 1 || dividebyH > 1)
                {
                    if(dividebyW > dividebyH)
                    {
                        divideBy = dividebyW;
                    }
                    else
                    {
                        divideBy = dividebyH;
                    }
                    imgShow = new Bitmap(Convert.ToInt32(Convert.ToDouble(imgOrg.Width) / divideBy), Convert.ToInt32(Convert.ToDouble(imgOrg.Height) / divideBy));
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution);
                    g = Graphics.FromImage(imgShow);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(imgOrg, new Rectangle(0, 0, Convert.ToInt32(Convert.ToDouble(imgOrg.Width) / divideBy), Convert.ToInt32(Convert.ToDouble(imgOrg.Height) / divideBy)), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel);
                    g.Dispose();
                }
                else
                {
                    imgShow = new Bitmap(imgOrg.Width, imgOrg.Height);
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution);
                    g = Graphics.FromImage(imgShow);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(imgOrg, new Rectangle(0, 0, imgOrg.Width, imgOrg.Height), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel);
                    g.Dispose();
                }
                imgOrg.Dispose();
                picbox.Image = null;
                return imgShow;
        }
        private void addPluginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Show the add plugin form
            PluginBrowser g = new PluginBrowser();
            this.WindowState = FormWindowState.Minimized;
            g.ShowDialog();
            this.WindowState = FormWindowState.Normal;
        }

        private void removePluginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(betterListView1.SelectedItems.Count > 0)
            {
                foreach (OpenPlugin plug in plugins)
                {
                    if(plug.Name == betterListView1.SelectedItems[0].Text)
                    {

                        //TODO: 
                        //Add plugin removal support.

                        //plugins.Remove(plug);
                        //File.Delete(betterListView1.SelectedItems[0].SubItems[1].Text);
                        //File.Delete(betterListView1.SelectedItems[0].SubItems[1].Text.Substring(0, betterListView1.SelectedItems[0].SubItems[1].Text.Length - 3) + "ini");
                        //betterListView1.Items.Remove(betterListView1.SelectedItems[0]);
                        //return;
                    }
                }
            }
        }

        private void betterListView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
